#pragma once
#include<iostream>
#include<unistd.h>
#include<functional>
#include<signal.h>
#include"Sock.hpp"
typedef std::function<void(int)>fun;
/* class HttpServer
{
    public:
    HttpServer(uint16_t port,fun func)
    :_port(port)
    ,_func(func)
    {
        _listensock=_sock.Socket();
        _sock.Bind(_listensock,_port);
        _sock.Listen(_listensock);

    }
    void start()
    {
      
        signal(SIGCHLD,SIG_IGN);//忽略子进程的退出信息
        
        for(;;)
        {
            uint16_t client_port;
            std::string client_ip;
          int servicesock=_sock.Accept(_listensock,&client_port,&client_ip);
          
          if(servicesock<0)
          {
            continue;
          }
          if(fork()==0)//创建子进程执行函数，为客户端提供服务
          {
            close(_listensock);
            _func(servicesock);
            close(servicesock);
            exit(0);
          }
          close(servicesock);

        }
    }
    ~HttpServer()
    {
        if(_listensock>=0)
        {
            close(_listensock);
        }
    }
    private:
    int _listensock;
    uint16_t _port;
    fun _func;
    Sock _sock;


}; */
class HttpServer
{
public:
    using func_t = std::function<void(int)>;
private:
    int listensock_;
    uint16_t port_;
    Sock sock;
    func_t func_;
public:
    HttpServer(const uint16_t &port, func_t func): port_(port),func_(func)
    {
        listensock_ = sock.Socket();
        sock.Bind(listensock_, port_);
        sock.Listen(listensock_);
    }
    void start()
    {
        signal(SIGCHLD, SIG_IGN);
        for( ; ; )
        {
            std::string clientIp;
            uint16_t clientPort = 0;
            int sockfd = sock.Accept(listensock_, &clientPort, &clientIp);
            if(sockfd < 0) continue;
            if(fork() == 0)
            {
                close(listensock_);
                func_(sockfd);
                close(sockfd);
                exit(0);
            }
            close(sockfd);
        }
    }
    ~HttpServer()
    {
        if(listensock_ >= 0) close(listensock_);
    }
};